package admin.controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.NewsModel;
import models.UserModel;
import admin.data.NewsData;
import admin.data.UserData;
import admin.forms.NewsForm;

public class AddNewsServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap check = new TreeMap();
		
		UserData userData = new UserData();
		ArrayList<UserModel> creators = userData.getCreator();
		
		NewsData newsData = new NewsData();
		NewsModel news = new NewsModel();
		
		request.setAttribute("check", check);
		request.setAttribute("news", news);
		request.setAttribute("form", "add");
		request.setAttribute("creators", creators);
		try {
            request.getRequestDispatcher("/admin/pages/form_news.jsp").forward(request, response);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {		
		UserData userData = new UserData();
		ArrayList<UserModel> creators = userData.getCreator();
		
		NewsData newsData = new NewsData();
		NewsModel news = new NewsModel();
		
		//Get value form and check valid
		TreeMap form = NewsForm.checkValid(request, news);
		news =(NewsModel) form.get("news");
		TreeMap check = (TreeMap) form.get("checkValid");
		
		//Save data
		if (check.size() == 0){
			news.setAutoSite("http://" + UrlHelper.fomatDomains(news.getUrl()));
			news.setId();
			newsData.insert(news);
			request.setAttribute("success", "Update success news " + news.getId());
		}
		
		request.setAttribute("check", check);
		request.setAttribute("news", news);
		request.setAttribute("form", "add");
		request.setAttribute("creators", creators);
		try {
	        request.getRequestDispatcher("/admin/pages/form_news.jsp").forward(request, response);
	    } catch (Exception e) {
	        //e.printStackTrace();
	    }
	}
}
